//
//  UITextView+Extension.swift
//  zhengwutong
//
//  Created by wangshuguan on 16/10/10.
//  Copyright © 2016年 wsg. All rights reserved.
//

import UIKit

var k_UITextViewExtensionKeyPlaceHolder = "k_UITextViewExtensionKeyPlaceHolder"
var k_UITextViewExtensionKeyPlaceHolderLabel = "k_UITextViewExtensionKeyPlaceHolderLabel"
extension UITextView {
    /// 需要在placeholder调用之后再调用
    var placeHolderLabel:UILabel{
        get{
            var label = objc_getAssociatedObject(self, &k_UITextViewExtensionKeyPlaceHolderLabel) as? UILabel
            if label == nil {
                label = UILabel(frame: CGRect(x: 8, y: 2, width: 300, height: 30))
                if #available(iOS 13.0, *) {
                    label?.textColor = .systemGroupedBackground
                } else {
                    // Fallback on earlier versions
                    label?.textColor = .groupTableViewBackground
                }
                label?.text = self.placeHolder
                label?.sizeToFit()
                self.addSubview(label!)
                objc_setAssociatedObject(self, &k_UITextViewExtensionKeyPlaceHolderLabel, label, .OBJC_ASSOCIATION_RETAIN)
            }
            return label!
        }
    }
    /// 需要先写text在写placeholdeer
    var placeHolder:String?{
        get{
            return objc_getAssociatedObject(self, &k_UITextViewExtensionKeyPlaceHolder) as? String
        }
        set{
            if (self.placeHolder == nil) {
                NotificationCenter.default.addObserver(self, selector: #selector(textViewChanged), name: UITextView.textDidChangeNotification, object: nil)
            }
            objc_setAssociatedObject(self, &k_UITextViewExtensionKeyPlaceHolder, newValue, .OBJC_ASSOCIATION_RETAIN)
                textViewChanged()
            }
        }
    @objc func textViewChanged() {
        self.placeHolderLabel.text = self.placeHolder
        self.placeHolderLabel.isHidden = !self.text.isEmpty
    }
}
